import { memo, useRef } from 'react';
import type { FC, PropsWithChildren } from 'react';
import ReactQuill, { Quill } from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { Form } from 'antd';
import { API_BASEURL, UPLOAD_URL } from '@/constants/api';
import { resUpload } from '@/services/common';
// @ts-ignore
import { ImageDrop } from 'quill-image-drop-module';
// @ts-ignore
import imageResize from 'quill-image-resize-module';
import './index.scss';

Quill.register('modules/imageResize', imageResize);

Quill.register('modules/imageDrop', ImageDrop);

const formats = [
  'bold',
  'italic',
  'underline',
  'strike',
  'blockquote',
  'list',
  'bullet',
  'indent',
  'link',
  'image',
  'size',
  'header',
  'color',
  'align',
  'direction',
  'background',
  'clean',
  'code-block',
  'script',
  'font',
];

const imageHandler = function () {
  const input = document.createElement('input');
  input.setAttribute('type', 'file');
  input.setAttribute('accept', 'image/*');
  input.click();
  input.onchange = () => {
    // @ts-ignore
    const file = input.files[0];
    const fd = new FormData();
    fd.append('file', file);
    //这里写自己的接口
    resUpload(fd).then((res) => {
      // @ts-ignore
      const range = this?.quill?.getSelection();
      // @ts-ignore
      this?.quill?.insertEmbed(
        range.index,
        'image',
        API_BASEURL + '/' + res[0]
      );
      let index = range ? range.index : 0;
      // @ts-ignore
      this?.quill?.setSelection(index + 1); //光标位置加1
    });
  };
};

const modules = {
  toolbar: {
    container: [
      ['bold', 'italic', 'underline', 'strike'], // toggled buttons
      ['blockquote', 'code-block'],
      [{ header: 1 }, { header: 2 }], // custom button values
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
      [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
      [{ direction: 'rtl' }], // text direction
      [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ color: [] }, { background: [] }], // dropdown with defaults from theme
      [{ align: [] }],
      ['link', 'image'],
      ['clean'], // remove formatting button
    ],
    handlers: {
      image: function () {
        imageHandler.call(this);
      },
    },
  },
  imageDrop: true,
  imageResize: {
    //调整大小组件。
    displayStyles: {
      backgroundColor: 'black',
      border: 'none',
      color: 'white',
    },
    modules: ['Resize', 'DisplaySize', 'Toolbar'],
  },
};

const RichEdit: FC<
  PropsWithChildren<{
    name?: string;
    label?: string;
    className?: string;
    placeholder?: string
  }>
> = ({ name,placeholder= "请输入书籍详情内容", label, className }) => {
  return (
    <Form.Item
      label={label}
      name={name}
      validateTrigger={'onSubmit'}
      rules={[
        {
          required: true,
          validator: (_, value) => {
            if (!value || value === '<p><br></p>') {
              return Promise.reject(placeholder);
            }
            return Promise.resolve();
          },
        },
      ]}
    >
      <ReactQuill
        placeholder={placeholder}
        theme="snow"
        modules={modules}
        formats={formats}
        className={className}
      />
    </Form.Item>
  );
};

export default memo(RichEdit);
